package al.jdbc.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import al.jdbc.dpbridge.DataSource;
import al.jdbc.dpbridge.MySqlDataSource;
import alOmrane.jdbc.beans.Courrier_depart;
import alOmrane.jdbc.beans.Envoyer_vers;
import alOmrane.jdbc.beans.Recevoir;

public class RecevoirDAO {
	private Connection db;
	@SuppressWarnings("unused")
	private DataSource ds;
	private ContactDAO odao = new ContactDAO(new MySqlDataSource("jdbc:mysql://localhost/gestion_courriers", "root"));
	private Courrier_arriveDAO cdao = new Courrier_arriveDAO(new MySqlDataSource("jdbc:mysql://localhost/gestion_courriers", "root"));
	private Statement sql;
	
	public RecevoirDAO(DataSource ds){
		db = ds.getConnection();
		this.ds = ds;
		try {
			sql = db.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public List<Recevoir> findByCourrier(Courrier_depart c){
		List<Recevoir> pjs = new ArrayList<Recevoir>();
		try {
			String query = "SELECT * FROM recevoir WHERE numero_courrier_depart="+c.getId()+" ;";

			ResultSet rs = sql.executeQuery(query);
			while(rs.next()){
				Recevoir ev = new Recevoir(Integer.parseInt(rs.getString(1)),
						c, 
						odao.findContactById(Integer.parseInt(rs.getString(3))));
				pjs.add(ev);
			}
			return pjs;
		}catch(Exception ex){
			return null;
		}
	}
	public boolean insert(Recevoir p){
		try{

			StringBuffer sb = new StringBuffer("INSERT INTO `recevoir` (`code_ctt`, `numero_courrier_depart`) VALUES " +
					"('"+p.getContact().getCode_ctt()+"', '"+p.getNum_courrier().getId()+"');");
			sql.executeUpdate(sb.toString());
			return true;
		}catch(Exception ex){
			ex.printStackTrace();
			return false;
		}
	}
	public boolean delete(int idCourrier){
		try{

			StringBuffer sb = new StringBuffer("DELETE FROM recevoir "+
					"WHERE numero_courrier_depart="+idCourrier+" ;");
			sql.executeUpdate(sb.toString());
			return true;
		}catch(Exception ex){
			System.out.println(ex.getMessage());
			return false;
		}
	}
}
